#include "MainWindow.h"
#include "ui_MainWindow.h"
#include "Marker.h"
#include "GraphicsScene.h"
#include <QtGui>
#include <QKeyEvent>
#include <Qt>

const int IdRole = Qt::UserRole;
int Gsize;
int Gshp_inx;

QColor col;
int rbID;


MainWindow::MainWindow(QWidget *parent):
    QMainWindow(parent),ui(new Ui::MainWindow),
    shortcutdelete(Qt::Key_Delete, this, SLOT(deletePressed()))

{
    ui->setupUi(this);

    markerlist = ui->ECSMarkerList;


    Escene=new GraphicsScene();  //Sets up Scene to use in QGraphicsView
    Escene->setSceneRect(QRect(0, 0, 661, 381));

    VEscene=new QGraphicsScene();  //Sets up Scene to use in QGraphicsView
    VEscene->setSceneRect(QRect(0, 0, 461, 301));

    Sscene=new QGraphicsScene();  //Sets up Scene to use in QGraphicsView
    Sscene->setSceneRect(QRect(0, 0, 661, 381));

    SCPscene=new QGraphicsScene();  //Sets up Scene to use in QGraphicsView
    SCPscene->setSceneRect(QRect(0, 0, 661, 381));

    Eview = ui->ECSView;            //Creates pointer to ECSView ui element
    VEview =ui->VSECSView;            //Creates pointer to ECSView ui element
    Sview=ui->SigfriedView;         //Creates pointer to SigfriedView ui element
    SCPview=ui->SCPView;         //Creates pointer to SigfriedView ui element


    Eview->setScene(Escene);
    Eview->setDragMode(QGraphicsView::RubberBandDrag);  //Allows you to select multiple items click-dragging the cursor
    Eview->setRenderHints(QPainter::Antialiasing);      //Enable antialiasing

    VEview->setScene(VEscene);
    VEview->setRenderHints(QPainter::Antialiasing);      //Enable antialiasing

    Sview->setScene(Sscene);
    Sview->setDragMode(QGraphicsView::RubberBandDrag);  //Allows you to select multiple items click-dragging the cursor
    Sview->setRenderHints(QPainter::Antialiasing);      //Enable antialiasing

    FileNameRec1="";  //FileNameRec records the last valid image file path
    FileNameRec2="";  //setting as blank at the start
    FileNameRec3="";

    //Read Default values
    Gsize=ui->SizeSpinBox->value();
    Gshp_inx=ui->ShapeMenu->currentIndex();
    rbID=radioButtonSelected();

    switch(rbID)
    {
    case 1:col=Qt::yellow;
        break;
    case 2:col=Qt::darkGreen;
        break;
    case 3:col=Qt::darkBlue;
        break;
    case 4:col=QColor(255,140,0,255);
        break;
    case 5:col=Qt::magenta;
        break;
    case 6:col=Qt::black;
        break;
    case 7:col=Qt::white;
        break;
    }


    QObject::connect(Escene, SIGNAL(markerPos(qreal,qreal)), this, SLOT(on_addMarker(qreal,qreal)));
    QObject::connect(Escene, SIGNAL(selectionChanged()), this, SLOT(on_selection()));
    QObject::connect(Escene, SIGNAL(markerPosChanged(qreal,qreal)), this, SLOT(on_addMarker(qreal, qreal)));
    QObject::connect(Escene, SIGNAL(listchanged()), this, SLOT(on_listchanged()));
    qApp->installEventFilter(this);
}


MainWindow::~MainWindow()
{
    delete Escene;
    delete Eview;
    delete Sscene;
    delete Sview;
    delete ui;

}

bool MainWindow::eventFilter(QObject *obj, QEvent *event)  //using eventfilter to implement the Mousemove signal
{

        if (event->type() == QEvent::MouseMove)
        {
            if (Eview->underMouse()==true) //restricting the operational area to Eview
            {
              QMouseEvent *mouseEvent = static_cast<QMouseEvent*>(event);
              Sceneposition=Eview->mapToScene(mouseEvent->pos());
              ui->xdisplay2->setText(Cursorx.setNum(Sceneposition.x())); //displayed in x box
              ui->ydisplay2->setText(Cursory.setNum(Sceneposition.y())); //displayed in y box
    //the coordinates are with respect to the object the cursor is on.
            }
            else  //display "N/A" when out of range
            {
                ui->xdisplay2->setText("N/A");
                ui->ydisplay2->setText("N/A");
            }
        }


    return false;
}



void MainWindow::on_ImageSelectButton1_clicked()
{
    QString fileName1 = QFileDialog::getOpenFileName(this,tr("Open File"), QDir::currentPath()); //Open File Dialog


    if (!fileName1.isEmpty())                    //Check to see if a file is selected. If a file is selected pass image create QImage object
    {
            QImage image1(fileName1);             //Load Image

            if (image1.isNull())                 //If not an image file display error
            {
                QMessageBox::information(this, tr("Sigfried Viewer"), tr("Cannot load %1.").arg(fileName1));

                return;
            }


            FileNameRec1=fileName1; //storing the valid namepath for future reference

            ui->ImageDirText1->setText(FileNameRec1);

            QPixmap img1 = QPixmap::fromImage(image1);
            Sscene->setBackgroundBrush(img1.scaled(661,381,Qt::IgnoreAspectRatio,Qt::SmoothTransformation));
            Sview->setScene(Sscene);


            Sview->setGeometry(QRect(310, 10, 661, 381));
            Sview->show();

     }

}


void MainWindow::on_ImageSelectButton2_clicked()
{

    QString fileName2 = QFileDialog::getOpenFileName(this,tr("Open File"), QDir::currentPath()); //Open File Dialog


    if (!fileName2.isEmpty())                    //Check to see if a file is selected. If a file is selected pass image create QImage object
    {
            QImage image2(fileName2);             //Load Image

            if (image2.isNull())                 //If not an image file display error
            {
                QMessageBox::information(this, tr("ECS Viewer"), tr("Cannot load %1.").arg(fileName2));

                return;
            }


            FileNameRec2=fileName2;

            ui->ImageDirText2->setText(FileNameRec2);

            QPixmap img2 = QPixmap::fromImage(image2);
            Escene->setBackgroundBrush(img2.scaled(661,381,Qt::IgnoreAspectRatio,Qt::SmoothTransformation));
            Eview->setScene(Escene);

            Eview->setGeometry(QRect(310, 10, 661, 381));
            Eview->show();

           //VEscene->setBackgroundBrush(img2.scaled(461,301,Qt::KeepAspectRatioByExpanding,Qt::SmoothTransformation));
           // VEview->setScene(VEscene);

           //VEview->setGeometry(QRect(0, 0, 465, 305));
           //VEview->show();

     }


}

void MainWindow::on_ImageSelectButton3_clicked()
{

    QString fileName3 = QFileDialog::getOpenFileName(this,tr("Open File"), QDir::currentPath()); //Open File Dialog


    if (!fileName3.isEmpty())                    //Check to see if a file is selected. If a file is selected pass image create QImage object
    {
            QImage image3(fileName3);             //Load Image

            if (image3.isNull())                 //If not an image file display error
            {
                QMessageBox::information(this, tr("SCP Viewer"), tr("Cannot load %1.").arg(fileName3));

                return;
            }


            FileNameRec3=fileName3;

            ui->ImageDirText3->setText(FileNameRec3);

            QPixmap img3 = QPixmap::fromImage(image3);
            SCPscene->setBackgroundBrush(img3.scaled(661,381,Qt::IgnoreAspectRatio,Qt::SmoothTransformation));
            SCPview->setScene(SCPscene);

            SCPview->setGeometry(QRect(310, 10, 661, 381));
            SCPview->show();

     }


}



void MainWindow::on_YellowMarker_clicked()
{

    Marker *marker;

    QList<QGraphicsItem *> items =Escene->items();
    QListIterator<QGraphicsItem *> i(items);

    while(i.hasNext())
    {
        marker=(Marker *)i.next();
        marker->setOutlineColor(Qt::yellow);

    }

    Eview->update();
    col=Qt::yellow;

}
void MainWindow::on_BlueMarker_clicked()
{

    Marker *marker;

    QList<QGraphicsItem *> items =Escene->items();
    QListIterator<QGraphicsItem *> i(items);

    while(i.hasNext())
    {
        marker=(Marker *)i.next();
        marker->setOutlineColor(Qt::darkBlue);

    }

    Eview->update();
    col=Qt::darkBlue;

}
void MainWindow::on_GreenMarker_clicked()
{

    Marker *marker;

    QList<QGraphicsItem *> items =Escene->items();
    QListIterator<QGraphicsItem *> i(items);

    while(i.hasNext())
    {
        marker=(Marker *)i.next();
        marker->setOutlineColor(Qt::darkGreen);

    }

    Eview->update();
    col=Qt::green;

}
void MainWindow::on_MagentaMarker_clicked()
{

    Marker *marker;

    QList<QGraphicsItem *> items =Escene->items();
    QListIterator<QGraphicsItem *> i(items);

    while(i.hasNext())
    {
        marker=(Marker *)i.next();
        marker->setOutlineColor(Qt::magenta);

    }

    Eview->update();
    col=Qt::magenta;

}
void MainWindow::on_OrangeMarker_clicked()
{

    Marker *marker;

    QList<QGraphicsItem *> items =Escene->items();
    QListIterator<QGraphicsItem *> i(items);

    while(i.hasNext())
    {
        marker=(Marker *)i.next();
        marker->setOutlineColor(QColor(255,140,0,255));

    }

    Eview->update();
    col=QColor(255,140,0,255);

}
void MainWindow::on_BlackMarker_clicked()
{

    Marker *marker;

    QList<QGraphicsItem *> items =Escene->items();
    QListIterator<QGraphicsItem *> i(items);

    while(i.hasNext())
    {
        marker=(Marker *)i.next();
        marker->setOutlineColor(Qt::black);

    }

    Eview->update();
    col=Qt::black;

}
void MainWindow::on_WhiteMarker_clicked()
{

    Marker *marker;

    QList<QGraphicsItem *> items =Escene->items();
    QListIterator<QGraphicsItem *> i(items);

    while(i.hasNext())
    {
        marker=(Marker *)i.next();
        marker->setOutlineColor(Qt::white);

    }

    Eview->update();
    col=Qt::white;

}



void MainWindow::on_ShapeMenu_activated(int index)
{
    Marker *marker;
    Marker::Shape shape = Marker::Shape(index-1);//ui->ShapeMenu->itemData(
                 //ui->ShapeMenu->currentIndex(), IdRole).toInt());

    QList<QGraphicsItem *> items =Escene->items();
    QListIterator<QGraphicsItem *> i(items);

    while(i.hasNext())
    {
        marker=(Marker *)i.next();
        marker->setShape(shape);
    }

    Eview->update();
    Gshp_inx=ui->ShapeMenu->currentIndex();
}

void MainWindow::on_SizeSpinBox_valueChanged(int index)
{
    Marker *marker;
    QList<QGraphicsItem *> items =Escene->items();
    QListIterator<QGraphicsItem *> i(items);

    while(i.hasNext())
    {
        marker=(Marker *)i.next();
        marker->setSize(ui->SizeSpinBox->value());
    }

    Eview->update();
    Gsize=ui->SizeSpinBox->value();
    Gshp_inx=ui->ShapeMenu->currentIndex();
}



short MainWindow::getSize()
{
    return Gsize;
}
QColor MainWindow::getColor()
{
    return col;
}


int MainWindow::getShape()
{
    return Gshp_inx;
}

int MainWindow::radioButtonSelected()
{
    if(ui->YellowMarker->isChecked())
        return 1;
    else if(ui->GreenMarker->isChecked())
        return 2;
    else if(ui->BlueMarker->isChecked())
        return 3;
    else if(ui->OrangeMarker->isChecked())
        return 4;
    else if(ui->MagentaMarker->isChecked())
        return 5;
    else if(ui->BlackMarker->isChecked())
        return 6;
    else if(ui->WhiteMarker->isChecked())
        return 7;
    else
        return 0;
}

void MainWindow::on_NoElectrodesSpinBox_valueChanged(int ElecValue)
{
        ElecValue=ui->NoElectrodesSpinBox->value();
        ui->ElectrodesTable->setRowCount(ElecValue);
}

void MainWindow::on_ImageDirText2_returnPressed()
{



    QString fileName2 = ui->ImageDirText2->text();

    if (!fileName2.isEmpty())                    //Check to see if a file is selected. If a file is selected pass image create QImage object
    {
            QImage image2(fileName2);             //Load Image

            if (image2.isNull())                 //If not an image file display error
            {
                QMessageBox::information(this, tr("ECS Viewer"), tr("Cannot load %1.").arg(fileName2));

                ui->ImageDirText2->setText(FileNameRec2); //restoring to last valid filename
                return;
            }

            FileNameRec2=fileName2; //storing for future reference

            //view = new QGraphicsView(ui->ECSView); //Creates pointer to ECSView ui element

            QPixmap img2 = QPixmap::fromImage(image2);
            Escene->setBackgroundBrush(img2.scaled(661,381));
            Eview->setScene(Escene);

            Eview->setGeometry(QRect(310, 10, 661, 381));
            Eview->show();

     }

}

void MainWindow::on_ImageDirText1_returnPressed()
{


    QString fileName1 = ui->ImageDirText1->text();

    if (!fileName1.isEmpty())                    //Check to see if a file is selected. If a file is selected pass image create QImage object
    {
            QImage image1(fileName1);             //Load Image

            if (image1.isNull())                 //If not an image file display error
            {
                QMessageBox::information(this, tr("ECS Viewer"), tr("Cannot load %1.").arg(fileName1));

                ui->ImageDirText1->setText(FileNameRec1);  //restoring to the last valid name
                return;
            }

            FileNameRec1=fileName1; //storing for future reference

            //view = new QGraphicsView(ui->ECSView); //Creates pointer to ECSView ui element

            QPixmap img1 = QPixmap::fromImage(image1);
            Sscene->setBackgroundBrush(img1.scaled(661,381));
            Sview->setScene(Sscene);

            Sview->setGeometry(QRect(310, 10, 661, 381));
            Sview->show();

     }
}

void MainWindow::on_ImageDirText3_returnPressed()
{



    QString fileName3 = ui->ImageDirText3->text();

    if (!fileName3.isEmpty())                    //Check to see if a file is selected. If a file is selected pass image create QImage object
    {
            QImage image3(fileName3);             //Load Image

            if (image3.isNull())                 //If not an image file display error
            {
                QMessageBox::information(this, tr("ECS Viewer"), tr("Cannot load %1.").arg(fileName3));

                ui->ImageDirText3->setText(FileNameRec3); //restoring to last valid filename
                return;
            }

            FileNameRec2=fileName3; //storing for future reference

            //view = new QGraphicsView(ui->ECSView); //Creates pointer to ECSView ui element

            QPixmap img3 = QPixmap::fromImage(image3);
            SCPscene->setBackgroundBrush(img3.scaled(661,381));
            SCPview->setScene(SCPscene);

            SCPview->setGeometry(QRect(310, 10, 661, 381));
            SCPview->show();

     }

}




void MainWindow::on_tabWidget_selected(const QString &arg1)
{
    Marker *marker;
    QList<QGraphicsItem *> items =Escene->items();
    QListIterator<QGraphicsItem *> i(items);

    while(i.hasNext())
    {
        marker=(Marker *)i.next();
        marker->setSelected(false);
    }

    Eview->update();

    QString fileName = "ECSview.png";
    QByteArray bytes;
    QBuffer buffer(&bytes);
    buffer.open(QIODevice::WriteOnly);
    QPixmap pixMap = QPixmap::grabWidget(Eview);

    VEscene->setBackgroundBrush(pixMap.scaled(461,301,Qt::IgnoreAspectRatio,Qt::SmoothTransformation));

}

void MainWindow::on_addMarker(qreal xpos1, qreal ypos1)
{
    QString xval;
    QString yval;

    ui->xdisplay1->setText(xval.setNum(xpos1));
    ui->ydisplay1->setText(yval.setNum(ypos1));
}

void MainWindow::on_selection()
{
    QString xval;
    QString yval;

    Marker *marker;
    QList<QGraphicsItem *> items = Escene->selectedItems();
    QListIterator<QGraphicsItem *> i(Escene->selectedItems());


    if (i.hasNext()==true)
    {
          marker=(Marker *)i.peekNext();


          if (items.size() == 1)
          {


             ui->xdisplay1->setText(xval.setNum(marker->getXpos()));
             ui->ydisplay1->setText(yval.setNum(marker->getYpos()));


          }

          else
          {
              ui->xdisplay1->setText("");
              ui->ydisplay1->setText("");


          }
      }
    else
    {
        ui->xdisplay1->setText("");
        ui->ydisplay1->setText("");
    }
}


void MainWindow::on_SCPLoadDataButton_clicked()
{

}

MainWindow* MainWindow::self()
{
    return this;
}

void MainWindow::deletePressed()
{
    if(!Escene->selectedItems().isEmpty())
    {
        while(!Escene->selectedItems().isEmpty())
        {
//            qDebug()<<Escene->selectedItems().last();
            Escene->removeItem(Escene->selectedItems().last());
        }


        on_listchanged();
    }
}

void MainWindow::on_listchanged()
{
    markerlist->clear();
    QString listdisplay; int markernum=0;
    scenelist = Escene->items(Qt::AscendingOrder);
//    qDebug()<<"scenelist is here!!"<<scenelist;
    QListIterator<QGraphicsItem*> Elist(scenelist);
    Elist.toFront();
    while(Elist.hasNext())
    {
        ++markernum;
        QGraphicsItem* nextone=Elist.next();
        listdisplay="Marker #"+QString::number(markernum, 'g', 3)+": "+QString::number(nextone->scenePos().x(), 'g', 6)+", "+QString::number(nextone->scenePos().y(), 'g', 6);
        markerlist->addItem(listdisplay);
    }

    return;
}

void MainWindow::on_actionUndo_activated()
{
    QListIterator<QGraphicsItem*> helperI(Escene->items());
    helperI.toFront();
    if (helperI.hasNext())
    {
        Escene->listHelper.append(helperI.next());
        qDebug()<<"undonehelper!"<<Escene->listHelper;
        Escene->removelastItem();
        on_listchanged();
    }
}

void MainWindow::on_actionRedo_activated()
{
    QListIterator<QGraphicsItem*> helperI(Escene->listHelper);
    helperI.toBack();
    if (helperI.hasPrevious())
    {
        Escene->addItem(helperI.previous());
        Escene->listHelper.removeLast();
        qDebug()<<"helper!!!!!!!!!!"<<Escene->listHelper;
        on_listchanged();
    }
}
